using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using System.Xml;

namespace Twitter
{
    public static class TwitterAPI
    {
        private static string proxyServer = null;

        public static string ProxyServer
        {
            get { return proxyServer; }
            set { proxyServer = value; }
        }
	


        public const int MAX_LENGTH = 140;

        private static string emailAddress;

        public static string EmailAddress
        {
            get { return emailAddress; }
            set { emailAddress = value; }
        }

        private static string password;

        public static string Password
        {
            get { return password; }
            set { password = value; }
        }

        public static string UpdateStatus(string status)
        {
            return UpdateStatus(status, emailAddress, password);
        }

        public static string UpdateStatus(string status, string Email, string Password)
        {
            if (!String.IsNullOrEmpty(status))
            {
                if (status.Length > MAX_LENGTH)
                    throw new ArgumentException("Status too long");
                string encodedStatus = HttpUtility.UrlEncode(status);
                HttpWebRequest hwr = (HttpWebRequest)WebRequest.CreateDefault(new System.Uri("http://twitter.com/statuses/update.xml?status=" + encodedStatus));

                hwr.Credentials = new System.Net.NetworkCredential(Email, Password);

                hwr.PreAuthenticate = true;
                hwr.Method = System.Net.WebRequestMethods.Http.Post;

                if (!String.IsNullOrEmpty(proxyServer))
                    hwr.Proxy = new WebProxy(proxyServer);


                try
                {
                    HttpWebResponse resp = (HttpWebResponse)hwr.GetResponse();
                    StreamReader sr = new StreamReader(resp.GetResponseStream());
                    String response = sr.ReadToEnd();

                    XmlDocument xdoc = new XmlDocument();
                    xdoc.LoadXml(response);
                    string statusURL = "http://www.twitter.com/{0}/statuses/{1}";

                    string screen_name = xdoc["status"]["user"]["screen_name"].InnerText;
                    string statusID = xdoc["status"]["id"].InnerText;
                    statusURL = string.Format(statusURL, screen_name, statusID);

                    return statusURL;

                }
                catch (Exception ex)
                {

                    throw new Exception("Request Failed", ex);
                }



            }
            else
                throw new ArgumentException("No Status Supplied");
        }
	
	
    }
}
